# algorithm/services.py
import numpy as np
from algorithm.models.tag_importance import TagImportance
from .models import TagValue
# 在models.__init__.py中导入后这两种写法均可以
from tag.models import Tag, AlgorithmTag

from django.db.models import F

from django.db.models import F

def list_all_tag_values():
    # 使用 select_related 来优化查询，连接到 AlgorithmTag 表，并按 tag_value 降序排列
    tag_values = TagValue.objects.select_related('tag').filter(tag__in=AlgorithmTag.objects.all()).annotate(
        tag_name=F('tag__tag_name'),
        tag_index=F('tag__index')
    ).order_by('-tag_value').values_list('tag_index', 'tag_name', 'tag_value')  # 获取字段值并按 tag_value 降序

    # 准备表头和分隔线
    header = f"{'Tag Index':<10}{'Tag Name':<30}{'Tag Value':>10}"
    print(header)
    print('-' * len(header))

    # 打印每个标签的详细信息，保证对齐
    for tag_index, tag_name, tag_value in tag_values:
        print(f"{tag_index:<10}{tag_name:<30}{tag_value:>10.2f}")


# 展示所有的TagImportance信息
def list_all_tag_importance():
    # 使用select_related来优化查询，直接连接到AlgorithmTag表
    tag_importances = TagImportance.objects.select_related('tag').filter(tag__in=AlgorithmTag.objects.all()).annotate(
        tag_name=F('tag__tag_name'),
        tag_index=F('tag__index')
    ).values('tag_index', 'tag_name', 'importance_score')

    # 准备表头和分隔线
    header = f"{'Tag Index':<10}{'Tag Name':<30}{'Importance Score':>20}"
    print(header)
    print('-' * len(header))

    # 打印每个标签的详细信息，保证对齐
    for tag_importance in tag_importances:
        print(f"{tag_importance['tag_index']:<10}{tag_importance['tag_name']:<30}{tag_importance['importance_score']:>20.2f}")
